#!/bin/bash

DEBIAN_VERSION=bullseye

# 获取参数
for opt in $@; do
    case "$opt" in
        debian-version*)
            # 指定了debian版本
            DEBIAN_VERSION=$(echo "$opt" | awk -F '=' '{print$2}')
            ;;
        *) ;;
    esac
done

# 更新软件源
cat > /etc/apt/sources.list << EOF
# 默认注释了源码仓库，如有需要可自行取消注释
deb http://mirrors.ustc.edu.cn/debian $DEBIAN_VERSION main contrib non-free
# deb-src http://mirrors.ustc.edu.cn/debian $DEBIAN_VERSION main contrib non-free
deb http://mirrors.ustc.edu.cn/debian $DEBIAN_VERSION-updates main contrib non-free
# deb-src http://mirrors.ustc.edu.cn/debian $DEBIAN_VERSION-updates main contrib non-free

# backports 软件源，请按需启用
# deb http://mirrors.ustc.edu.cn/debian $DEBIAN_VERSION-backports main contrib non-free
# deb-src http://mirrors.ustc.edu.cn/debian $DEBIAN_VERSION-backports main contrib non-free
EOF
sync

UPDATED=0

function update()
{
    echo "I: 更新软件源"
    apt-get update > /dev/null
    UPDATED=1
}

echo "I: 安装预置软件"
# 获取安装的软件包
if [ ! -f customs/packes.list.tmp ]; then
    touch customs/packes.list.tmp
fi

if [ -f customs/packes.list ]; then
    for line in $(cat customs/packes.list); do
        echo $line | grep "^#" &> /dev/null
        if (( $? != 0 )); then
            INSTALLED=$(cat customs/packes.list.tmp | grep "^$line$" | wc -l)
            if (( $INSTALLED == 0 )); then
                if (( $UPDATED == 0 )); then 
                    update
                fi
                echo "I: 安装 $line"
                apt-get install -y $line > /dev/null
                echo "$line" >> customs/packes.list.tmp
            fi
        fi
    done
fi
